package com.wrupple.vegetate.client.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.wrupple.vegetate.client.util.JsArrayList;
import com.wrupple.vegetate.domain.CatalogDescriptor;
import com.wrupple.vegetate.domain.FieldDescriptor;

public final class JsCatalogDescriptor extends JavaScriptObject implements
		CatalogDescriptor {

	protected JsCatalogDescriptor() {
		super();
	}

	@Override
	public native String getDescriptiveField() /*-{
		return this.descriptiveField;
	}-*/;

	@Override
	public native String getKeyField() /*-{
		return this.keyField;
	}-*/;

	@Override
	public native String getId() /*-{
		return this.id;
	}-*/;

	@Override
	public native String getName() /*-{
		return this.name;
	}-*/;

	@Override
	public native String getClazz() /*-{
		return this.clazz;
	}-*/;

	@Override
	public FieldDescriptor getFieldDescriptor(String id) {
		JsArray<JsFieldDescriptor> arr = getFieldArray();
		JsFieldDescriptor  temp ;
		String tempId;
		for(int i = 0 ; i < arr.length(); i++){
			temp = arr.get(i);
			if(temp!=null ){
				tempId = temp.getId();
				if(id.equals(tempId)){
					return temp;
				}
			}
		}
		return null;
	}
	
	

	private native JsArray<JsFieldDescriptor> getFieldArray()  /*-{
		return this.fields;
	}-*/;

	@Override
	public Collection<String> getFieldNames() {
		List<String> list = JsArrayList.arrayAsListOfString(getFieldNamesAsJsArray());
		return list;
	}

	public native JsArrayString getFieldNamesAsJsArray() /*-{
		return this.fieldNames;
	}-*/;

	@Override
	public Collection<FieldDescriptor> getFields() {
		JsArrayString names = getFieldNamesAsJsArray();
		if(names==null){
			return null;
		}
		List<FieldDescriptor> regreso = new ArrayList<FieldDescriptor>(names.length());
		FieldDescriptor temp;
		String name;
		for(int i = 0 ; i < names.length(); i++){
			name = names.get(i);
			temp = getFieldDescriptor(name);
			regreso.add(temp);
		}
		return regreso;
	}
}
